package ctu.kfad.run.memory;

import ctu.kfad.run.stack.AStackObject;
import ctu.kfad.run.stack.IntegerStackObject;
import ctu.kfad.run.stack.ReferenceStackObject;

public class FieldByteConverter {

    public static byte[] covertToBytes(String signature, AStackObject value) {
        switch (signature) {
            case ClassSizeDescriptor.SIGNATURE_INTEGER:
                return FieldValueConverter.toBytes(((IntegerStackObject) value).getIntValue());
            case ClassSizeDescriptor.SIGNATURE_BOOLEAN:
                final IntegerStackObject byteValue = (IntegerStackObject) value;
                return FieldValueConverter.toBytes(byteValue.getBooleanValue());
            case ClassSizeDescriptor.SIGNATURE_INTEGER_ARRAY:
            case ClassSizeDescriptor.SIGNATURE_BOOLEAN_ARRAY:
            case ClassSizeDescriptor.SIGNATURE_REFERENCE_ARRAY:
            case ClassSizeDescriptor.SIGNATURE_REFERENCE:
            case ClassSizeDescriptor.SIGNATURE_STRING:
                return FieldValueConverter.toBytes(((ReferenceStackObject) value).getReference());
            default:
                throw new RuntimeException("Signature was not recognized" + signature);
        }
    }

    public static AStackObject covertFromBytes(String signature, byte[] bytes) {
        switch (signature) {
            case ClassSizeDescriptor.SIGNATURE_INTEGER:
                return new IntegerStackObject(FieldValueConverter.toInt(bytes));
            case ClassSizeDescriptor.SIGNATURE_BOOLEAN:
                return new IntegerStackObject(FieldValueConverter.toBoolean(bytes));
            case ClassSizeDescriptor.SIGNATURE_INTEGER_ARRAY:
            case ClassSizeDescriptor.SIGNATURE_BOOLEAN_ARRAY:
            case ClassSizeDescriptor.SIGNATURE_REFERENCE_ARRAY:
            case ClassSizeDescriptor.SIGNATURE_REFERENCE:
            case ClassSizeDescriptor.SIGNATURE_STRING:
                return new ReferenceStackObject(FieldValueConverter.toInt(bytes));
            default:
                throw new RuntimeException("Signature was not recognized " + signature);
        }
    }
}
